import fs from 'fs';
import lodash from 'lodash';
import puppeteer from "../../../lib/puppeteer/puppeteer.js";
import {
    createAGroupFolder,
    deletePlayerData,
    getPlayerData,
    isGroupExist,
    isPlayerExist,
    PLUGIN_PATH,
    storagePlayerData,
    getConfig,
    formatCurrency,
    checkPermission
} from '../function/function.js';

// 读取JSON文件
const copywriting = JSON.parse(fs.readFileSync('plugins/Slave-Market/resources/data/workCopywriting.json', 'utf-8'));

export class Sm extends plugin {
    constructor() {
        super({
            name: '[Sm]打工',
            dsc: '打工',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/](一键)?(打工|工作)$/, fnc: 'work' },
                { reg: /^[#\/]重置打工冷却$/, fnc: 'resetWorkCooldown' }
            ]
        })
    }

    async work(e) {
        if (!e.isGroup) return e.reply(['该游戏只能在群内使用']);
        const ID = [e.user_id, e.group_id];

        // 读取配置
        const config = getConfig();

        // 检查群组和玩家是否存在，不存在则创建
        if (!isGroupExist(ID[1])) createAGroupFolder(ID[1]);
        if (!isPlayerExist(ID[1], ID[0])) {
            storagePlayerData(ID[1], ID[0], {
                currency: 0,
                slave: [],
                value: 100,
                lastWorkingTime: 0,
                master: '',
                nickname: e.sender.card || e.sender.nickname
            });
        } else {
            // 更新昵称
            const userData = await getPlayerData(ID[1], ID[0]);
            storagePlayerData(ID[1], ID[0], userData, e.sender.card || e.sender.nickname);
        }

        try {
            const userData = await getPlayerData(ID[1], ID[0]);
            const { currency, slave, value, lastWorkingTime, master } = userData;

            const currentSecond = Math.floor(Date.now() / 1000);
            const remainingTime = {
                h: Math.floor(Math.abs(currentSecond - lastWorkingTime) / 3600),
                m: Math.floor(Math.abs(currentSecond - lastWorkingTime) % 3600 / 60),
                s: Math.abs(currentSecond - lastWorkingTime) % 60
            };

            // 检查冷却时间
            if (!checkPermission(e) && currentSecond - lastWorkingTime < 0) {
                const timeMsg = `每${config.work.cooldown / 3600}小时一次，剩余CD：`;
                const timeReply = remainingTime['h'] > 0 ? `${remainingTime['h']}时${remainingTime['m']}分${remainingTime['s']}秒` :
                    remainingTime['m'] > 0 ? `${remainingTime['m']}分${remainingTime['s']}秒` : `${remainingTime['s']}秒`;
                return e.reply([segment.at(ID[0]), `${timeMsg}${timeReply}`]);
            }

            let wages = 0, msg = '';
            let workData = [];
            let hasMaster = false;
            let masterCut = 0;
            let masterName = '';
            let finalIncome = 0;
            
            if (slave.length === 0) {
                // 如果没奴隶
                if (e.isMaster) {
                    // 如果是Bot主人
                    wages = lodash.random(100, 2000) + lodash.random(parseInt(value / 10), parseInt(value / 5));
                    workData.push({ 
                        name: e.sender.card || e.sender.nickname, 
                        work: lodash.sample(copywriting.slaveowner),
                        income: `${wages}金币` 
                    });
                    
                    // 处理主人分成
                    if (master && master !== '') {
                        if (isPlayerExist(ID[1], master)) {
                            const masterData = await getPlayerData(ID[1], master);
                            hasMaster = true;
                            masterCut = Math.floor(wages * 0.5);
                            finalIncome = wages - masterCut;
                            
                            // 获取主人昵称
                            try {
                                const masterInfo = await Bot.pickGroup(ID[1]).pickMember(master).getInfo();
                                masterName = masterInfo ? (masterInfo.card || masterInfo.nickname) : `主人(${master})`;
                            } catch (error) {
                                masterName = `主人(${master})`;
                            }
                            
                            // 更新金币
                            userData['currency'] = formatCurrency(userData['currency'] + finalIncome);
                            masterData['currency'] = formatCurrency(masterData['currency'] + masterCut);
                            storagePlayerData(ID[1], master, masterData);
                            
                            msg = `您是尊贵的奴隶主\r【您】${lodash.sample(copywriting.slaveowner)}${wages}金币` +
                                  `\r作为${masterName}的奴隶，您上缴50%收入(${masterCut}金币)给主人` +
                                  `\r实际获得${finalIncome}金币\r当前共有${currency + finalIncome}金币`;
                        } else {
                            // 主人不存在，清除主人字段
                            userData['master'] = '';
                            finalIncome = wages;
                            userData['currency'] = formatCurrency(userData['currency'] + wages);
                            msg = `您是尊贵的奴隶主\r【您】${lodash.sample(copywriting.slaveowner)}${wages}金币\r当前共有${currency + wages}金币`;
                        }
                    } else {
                        finalIncome = wages;
                        userData['currency'] = formatCurrency(userData['currency'] + wages);
                        msg = `您是尊贵的奴隶主\r【您】${lodash.sample(copywriting.slaveowner)}${wages}金币\r当前共有${currency + wages}金币`;
                    }
                    
                    userData['lastWorkingTime'] = currentSecond + config.work.slaveownerCooldown;
                    storagePlayerData(ID[1], ID[0], userData);
                } else {
                    // 如果是群友
                    wages = lodash.random(10, 100) + lodash.random(parseInt(value / 20), parseInt(value / 10));
                    workData.push({ 
                        name: e.sender.card || e.sender.nickname, 
                        work: lodash.sample(copywriting.success),
                        income: `${wages}金币` 
                    });
                    
                    // 处理主人分成
                    if (master && master !== '') {
                        if (isPlayerExist(ID[1], master)) {
                            const masterData = await getPlayerData(ID[1], master);
                            hasMaster = true;
                            masterCut = Math.floor(wages * 0.5);
                            finalIncome = wages - masterCut;
                            
                            // 获取主人昵称
                            try {
                                const masterInfo = await Bot.pickGroup(ID[1]).pickMember(master).getInfo();
                                masterName = masterInfo ? (masterInfo.card || masterInfo.nickname) : `主人(${master})`;
                            } catch (error) {
                                masterName = `主人(${master})`;
                            }
                            
                            // 更新金币
                            userData['currency'] = formatCurrency(userData['currency'] + finalIncome);
                            masterData['currency'] = formatCurrency(masterData['currency'] + masterCut);
                            storagePlayerData(ID[1], master, masterData);
                            
                            msg = `你没有奴隶只能自己去打工\r【你】${lodash.sample(copywriting.success)}${wages}金币` +
                                  `\r作为${masterName}的奴隶，你上缴50%收入(${masterCut}金币)给主人` +
                                  `\r实际获得${finalIncome}金币\r当前共有${currency + finalIncome}金币`;
                        } else {
                            // 主人不存在，清除主人字段
                            userData['master'] = '';
                            finalIncome = wages;
                            userData['currency'] = formatCurrency(userData['currency'] + wages);
                            msg = `你没有奴隶只能自己去打工\r【你】${lodash.sample(copywriting.success)}${wages}金币\r当前共有${currency + wages}金币`;
                        }
                    } else {
                        finalIncome = wages;
                        userData['currency'] = formatCurrency(userData['currency'] + wages);
                        msg = `你没有奴隶只能自己去打工\r【你】${lodash.sample(copywriting.success)}${wages}金币\r当前共有${currency + wages}金币`;
                    }
                    
                    userData['lastWorkingTime'] = currentSecond + config.work.cooldown;
                    storagePlayerData(ID[1], ID[0], userData);
                }
                
                // 随机触发费用事件
                if (lodash.random(1, 10) <= 2) { // 20%的概率触发
                    const expenseEvent = lodash.sample(copywriting.expenses);
                    const expenseAmount = parseInt(expenseEvent.match(/\d+/)[0]);
                    userData['currency'] = formatCurrency(Math.max(0, userData['currency'] - expenseAmount));
                    msg += `\n${expenseEvent}`;
                    storagePlayerData(ID[1], ID[0], userData);
                }
                
                return e.reply(msg);
            } else {
                // 有奴隶时的打工逻辑
                // 遍历奴隶
                for (const QQ of slave) {
                    if (!isPlayerExist(ID[1], QQ)) {
                        deletePlayerData(ID[1], QQ);
                        userData['slave'] = userData['slave'].filter(a => a !== QQ);
                        storagePlayerData(ID[1], ID[0], userData);
                        continue;
                    }
                    // 确保slaveData和values正确初始化
                    let slaveData = await getPlayerData(ID[1], QQ);
                    let values = slaveData['value'];

                    // 随机打工收入
                    let wages_ = lodash.random(5, 20) + lodash.random(parseInt(values / 20), parseInt(values / 10));
                    const memberInfoList = Object.fromEntries([...await Bot.pickGroup(ID[1]).getMemberMap()]);
                    // 检查奴隶是否存在
                    if (!memberInfoList[QQ]) {
                        deletePlayerData(ID[1], QQ);
                        continue;
                    }
                    // 检查奴隶是否在线
                    if (lodash.random(1, 10) !== 1) {
                        const workMsg = lodash.sample(copywriting.success);
                        // 奴隶在线时的打工收入
                        workData.push({ name: memberInfoList[QQ]['nickname'], work: workMsg, income: `${wages_}金币` });
                    } else {
                        wages_ = 0;
                        const workMsg = lodash.sample(copywriting.failure).replace(/\[A\]/g, `【${memberInfoList[QQ]['nickname']}】`).replace(/\[C\]/g, slaveData['value']).replace(/\[D\]/g, slaveData['value'] - 20);
                        workData.push({ name: memberInfoList[QQ]['nickname'], work: workMsg, income: '' });
                        slaveData['value'] = parseFloat(Math.max(0, slaveData['value'] - 20).toFixed(1));
                        storagePlayerData(ID[1], QQ, slaveData);
                    }
                    wages += wages_;
                }
                
                finalIncome = wages;
                let hasExpense = false;
                let expenseText = '';
                let expenseAmount = 0;
                
                // 处理主人分成
                if (master && master !== '') {
                    if (isPlayerExist(ID[1], master)) {
                        const masterData = await getPlayerData(ID[1], master);
                        hasMaster = true;
                        masterCut = Math.floor(wages * 0.5);
                        finalIncome = wages - masterCut;
                        
                        // 获取主人昵称
                        try {
                            const masterInfo = await Bot.pickGroup(ID[1]).pickMember(master).getInfo();
                            masterName = masterInfo ? (masterInfo.card || masterInfo.nickname) : `主人(${master})`;
                        } catch (error) {
                            masterName = `主人(${master})`;
                        }
                        
                        // 更新金币
                        userData['currency'] = formatCurrency(userData['currency'] + finalIncome);
                        masterData['currency'] = formatCurrency(masterData['currency'] + masterCut);
                        storagePlayerData(ID[1], master, masterData);
                    } else {
                        // 主人不存在，清除主人字段
                        userData['master'] = '';
                        userData['currency'] = formatCurrency(userData['currency'] + wages);
                    }
                } else {
                    userData['currency'] = formatCurrency(userData['currency'] + wages);
                }
                
                // 随机触发费用事件
                if (lodash.random(1, 10) <= 2) { // 20%的概率触发
                    const expenseEvent = lodash.sample(copywriting.expenses);
                    hasExpense = true;
                    expenseText = expenseEvent;
                    
                    const match = expenseEvent.match(/\d+/);
                    if (match) {
                        expenseAmount = parseInt(match[0]);
                        userData['currency'] = formatCurrency(Math.max(0, userData['currency'] - expenseAmount));
                    }
                }
                
                userData['lastWorkingTime'] = currentSecond + config.work.cooldown;
                storagePlayerData(ID[1], ID[0], userData);
                
                // 用于渲染图像的数据
                const finalBalance = userData.currency;
                const renderData = {
                    tplFile: 'plugins/Slave-Market/resources/html/work/index.html',
                    filePath: `${PLUGIN_PATH}/resources/`,
                    workData,
                    workTitle: '您的奴隶们出去打工了',
                    
                    // 基本信息
                    playerName: e.sender.card || e.sender.nickname,
                    originalIncome: wages,
                    finalIncome: finalIncome,
                    currentBalance: finalBalance,
                    
                    // 主人分成信息
                    hasMaster,
                    masterName,
                    masterCut,
                    
                    // 支出信息
                    hasExpense,
                    expenseText,
                    expenseAmount
                };
                
                // 生成图片并发送
                const image = await puppeteer.screenshot('打工详情', renderData);
                return e.reply([image]);
            }

        } catch (error) {
            logger.error('处理打工请求时出错:', error);
            logger.error(error.stack || error);
            return e.reply(['处理请求时出错，请稍后再试。']);
        }
    }

    async resetWorkCooldown(e) {
        if (!e.isMaster) return e.reply('只有主人才能重置冷却时间');
        if (!e.isGroup) return e.reply('该命令只能在群内使用');

        try {
            const groupId = e.group_id;
            const files = fs.readdirSync(`plugins/Slave-Market/data/player/${groupId}`);
            
            for (const file of files) {
                if (file.endsWith('.json')) {
                    const playerData = await getPlayerData(groupId, file.replace('.json', ''));
                    playerData.lastWorkingTime = 0;
                    storagePlayerData(groupId, file.replace('.json', ''), playerData);
                }
            }
            
            return e.reply('已重置本群所有成员的打工冷却时间');
        } catch (error) {
            logger.error('重置打工冷却时间时出错:', error);
            return e.reply('重置冷却时间时出错，请稍后再试');
        }
    }
}
